//
//  ViewController.swift
//  YitihuaPH
//
//  Created by Kai Kang on 2019/1/14.
//  Copyright © 2019 Kai Kang. All rights reserved.
//

import UIKit
import CoreBluetooth


class ViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    var dataSource = [CBPeripheral]()
    let btmanager = BlueManager.share
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.tableFooterView = UIView()
        tableView.dataSource = self
        tableView.delegate = self
        
        btmanager.discoverPeripheral = { [weak self] (peripheral) in
            if let `self` = self, !self.dataSource.contains(peripheral) {
                self.dataSource.append(peripheral)
                self.tableView.reloadData()
            }
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(connted), name: NSNotification.Name.init("connected"), object: nil)
    }
    
    @objc
    func connted() {
        let debugVC = DeviceDebugViewController()
        self.navigationController?.pushViewController(debugVC, animated: true)
    }

    @IBAction func searchAction(_ sender: Any) {
        dataSource.removeAll()
        tableView.reloadData()
        btmanager.startScan()
    }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell.init(style: .default, reuseIdentifier: nil)
        cell.textLabel?.text = dataSource[indexPath.row].name
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 45
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        btmanager.connect(peripheral: dataSource[indexPath.row])
    }
}
